#ifndef __RS485_H__
#define __RS485_H__

#include <bits/stdc++.h>
#include "./libmodbus/modbus.h"

using namespace std;


class RS485_Handler
{
private:
    // static RS485_Handler *instance;
    static shared_ptr<RS485_Handler> instance;

    modbus_t* ctx;
    mutex update_slaves_id_lock;
    mutex rd_lock;
    thread *inner_thread = nullptr;

    bool m_thread_safe = false;
    bool m_init_flag = false;

    bool m_slave_reset_error_flag = false;
    bool m_slave_can_error_flag = false;

    unordered_set<int> m_slaves_id;

    int WR_Reg_Inner(int slave_id, vector<uint16_t> &data, int addr, int nb, int mode);
    void _inner_exec();
    RS485_Handler();
public:
    static shared_ptr<RS485_Handler> GetInstance() {
        if(!instance)
            instance = shared_ptr<RS485_Handler>(new RS485_Handler());
        return instance;
    }
    void init(string dev, int band_rate, bool thread_safe, bool debug_mode = false);
    int ReadInputRegister(int slave_id, vector<uint16_t> &data, int addr, int nb = 1);
    int ReadHoldingRegister(int slave_id, vector<uint16_t> &data, int addr, int nb = 1);
    int WriteHoldingRegister(int slave_id, vector<uint16_t> &data, int addr, int nb = 1);
    void UpdateSlavesID(int slave_id);

    ~RS485_Handler();



};





#endif